<template>
  <div class="advanced-setting-container">
    <el-menu
      :default-active="activeIndex"
      class="setting-menu"
      text-color="#666"
      @select="handleSelect">
      <template v-for="item in menuList">
        <el-menu-item v-if="showSettingTab(item.id)" :key="item.id" :index="item.id">
          <img :src="item.id === activeIndex ? item.activeIcon : item.icon" class="setting-menu-icon">
          <el-badge :is-dot="item.isDot">{{ item.name }}</el-badge>
        </el-menu-item>
      </template>
    </el-menu>
    <div class="setting-main-container">
      <div class="setting-main-content">
        <ProcessSetting v-show="activeIndex === '1'" ref="processSettingRef" :process-type="processType" />
        <ListSetting
          v-show="activeIndex === '2'"
          ref="listSettingRef"
          :form-list="formList"
          :list="advancedOptions.list"
          :card="advancedOptions.card || {}"
          :config-fields="filterFields"
          @statusCheck="statusCheck" />
        <EventSetting
          v-show="activeIndex === '3'"
          ref="eventSettingRef"
          :config-fields="eventFields"
          @statusCheck="statusCheck"
          @eventNameChange="$emit('eventNameChange', $event)" />
        <NoticeSetting v-show="activeIndex === '4'" ref="noticeSettingRef" :notice="advancedOptions.notice" @statusCheck="statusCheck" />
        <PermissionsSetting v-show="activeIndex === '5'" ref="permissionsSettingRef" :permission-fields="permissionFields" @statusCheck="statusCheck" />
        <DataSetting v-show="activeIndex === '6'" ref="dataSettingRef" :sync-status="syncStatus" :form-list="formList" @statusCheck="statusCheck" @syncData="syncData"/>
      </div>
    </div>
  </div>
</template>

<script>
import ProcessSetting from './processSetting';
import ListSetting from './listSetting';
import EventSetting from './eventSetting';
import NoticeSetting from './noticeSetting';
import PermissionsSetting from './permissionsSetting';
import DataSetting from './dataSetting';
// img
import eventIcon from '@/assets/customProcess/event.png';
import eventActiveIcon from '@/assets/customProcess/event-active.png';
import listIcon from '@/assets/customProcess/list.png';
import listActiveIcon from '@/assets/customProcess/list-active.png';
import noticeIcon from '@/assets/customProcess/notice.png';
import noticeActiveIcon from '@/assets/customProcess/notice-active.png';
import permissionIcon from '@/assets/customProcess/permission.png';
import permissionActiveIcon from '@/assets/customProcess/permission-active.png';
import processIcon from '@/assets/customProcess/process.png';
import processActiveIcon from '@/assets/customProcess/process-active.png';
import dataIcon from '@/assets/auditProcess/data.png';
import dataActiveIcon from '@/assets/auditProcess/data_active.png';
import { EventBus } from '@/utils/eventBus';
// api
import { getCommonApprovalPermissions } from '@/api/approvalModule';
// utils
import { allTargets } from './settingTargets';

export default {
  components: {
    ProcessSetting,
    ListSetting,
    EventSetting,
    NoticeSetting,
    PermissionsSetting,
    DataSetting
  },
  props: {
    formList: {
      type: Array,
      default: () => []
    },
    isFixed: {
      type: Boolean,
      default: false
    },
    isAdmin: {
      type: Boolean,
      default: false
    },
    moduleId: {
      type: Number | String,
      default: ''
    },
    advancedOptions: {
      type: Object,
      default: () => ({})
    },
    syncStatus: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      activeIndex: '1',
      allConfigFields: [], // 除了列表字段配置和通知模板外的所有字段（包括子表单内部字段）
      hasPermissionSet: false,
      hasSyncData: false,
      listStatus: false,
      exportStatus: false,
      cardStatus: false,
      eventStatus: false,
      noticeStatus: false,
      permissionStatus: false,
      dataStatus: false,
      processType: 0
    };
  },
  computed: {
    menuList() {
      const baseMenu = [{
        id: '1',
        name: '流程设置',
        icon: processIcon,
        activeIcon: processActiveIcon
      }];
      const customMenu = [
        { id: '2', name: '列表设置', icon: listIcon, activeIcon: listActiveIcon, isDot: this.listStatus || this.exportStatus || this.cardStatus },
        { id: '3', name: '事件设置', icon: eventIcon, activeIcon: eventActiveIcon, isDot: this.eventStatus },
        { id: '4', name: '通知模板', icon: noticeIcon, activeIcon: noticeActiveIcon, isDot: this.noticeStatus },
        { id: '5', name: '权限设置', icon: permissionIcon, activeIcon: permissionActiveIcon, isDot: this.permissionStatus },
        { id: '6', name: '数据同步', icon: dataIcon, activeIcon: dataActiveIcon, isDot: this.dataStatus }
      ];
      return this.isFixed ? baseMenu : [...baseMenu, ...customMenu];
    },
    // 事件目标字段选择排除类型
    targetExcludeTargets() {
      return ['createUser', 'createTime', 'workflowId', 'formulaInput'];
    },
    // 事件设置选择字段
    eventFields() {
      return this.allConfigFields.filter(item =>
        !item.isSubTable && !this.targetExcludeTargets.includes(item.type)
      );
    },
    // 权限可读组件字段
    permissionFields() {
      return this.allConfigFields.filter(item => item.type !== 'grid');
    },
    // 筛选项配置排除字段
    filterExcludeTargets() {
      return ['subform', 'linkForm', 'upAttachment', 'associatedApproval', 'richEditor'];
    },
    // 筛选项配置默认字段
    filterSettingDefaultFields() {
      return [
        { key: 'currentNode', name: '当前节点' },
        { key: 'currentHandler', name: '当前处理人' },
        { key: 'status', name: '状态' },
        { key: 'isExpedited', name: '是否加急' }
      ];
    },
    // 筛选项配置配置字段
    filterFields() {
      const filterConfigFields = this.allConfigFields.filter(item =>
        !this.filterExcludeTargets.includes(item.type)
      );
      return [...this.filterSettingDefaultFields, ...filterConfigFields];
    },
    // 权限设置权限
    showPermissionsSetting() {
      return this.isAdmin || this.hasPermissionSet || !this.moduleId;
    },
    // 数据同步权限
    showSyncData() {
      return this.isAdmin || this.hasSyncData || !this.moduleId;
    },
    // tab提示
    isShowAdvancedDot() {
      return this.listStatus || this.exportStatus || this.cardStatus || this.eventStatus || this.noticeStatus || this.permissionStatus || this.dataStatus;
    }
  },
  watch: {
    advancedOptions: {
      handler: function(val) {
        this.initCheck(val);
      }
    }
  },
  created() {
    EventBus.$on('formOptionsChange', (data) => {
      this.$nextTick(() => {
        this.setConfigField(_.cloneDeep(this.formList));
      });
    });
    if (this.moduleId && !this.isFixed) {
      this.queryPermissions();
    }
    this.$nextTick(() => {
      this.statusCheck();
    });
  },
  methods: {
    // 设置页面操作对应权限
    queryPermissions() {
      getCommonApprovalPermissions(this.moduleId).then(res => {
        if (res.code === 200) {
          this.hasPermissionSet = res.data.hasPermissionSet;
          this.hasSyncData = res.data.hasSyncData;
        }
      });
    },
    initCheck(advancedOptions) {
      const { list, notice, exportList } = advancedOptions;
      this.noticeStatus = !notice.length ? true : notice.filter(it => it.isCheck).length < 1;
      const fieldArr = list.field.filter(it => it.isCheck);
      const filterArr = list.filter.filter(it => it.isCheck);
      this.listStatus = fieldArr.length < 1 && filterArr.length < 1;
      this.exportStatus = !exportList || !exportList.length ? false : exportList.filter(it => it.isCheck).length < 1;
    },
    syncData(formItem) {
      this.$emit('syncData', formItem);
    },
    statusCheck() {
      this.$nextTick(() => {
        this.listStatus = this.$refs['listSettingRef'].validate(); // 列表设置
        this.exportStatus = this.$refs['listSettingRef'].$refs['exportSettingRef'].validate(); // 列表导出设置
        this.noticeStatus = this.$refs['noticeSettingRef'].validate(); // 通知模板
        this.$refs['eventSettingRef'].$refs['dynamicEditTableRef'].validate().then(() => {
          this.eventStatus = false;
          this.$emit('statusCheck');
        }).catch(() => {
          this.eventStatus = true;
          this.$emit('statusCheck');
        }); // 事件设置
        this.$refs['listSettingRef'].$refs['cardSettingRef'].validate().then(() => { // 卡片视图配置
          this.cardStatus = false;
          this.$emit('statusCheck');
        }).catch(() => {
          this.cardStatus = true;
          this.$emit('statusCheck');
        });
        this.permissionStatus = this.$refs['permissionsSettingRef'].validate(); // 权限设置
        this.dataStatus = !this.$refs['dataSettingRef'].validate(); // 数据同步
        this.$emit('statusCheck');
      });
    },
    setConfigField(list) {
      const baseList = _.cloneDeep(this.allConfigFields) || [];
      this.allConfigFields = [];
      this.generateFields(list);
      // 重新生成后通知项和筛选项的勾选数据会丢失，重新赋值
      this.setSelectData(baseList);
      this.allUserSelectFields();
      this.storeAllDeptSelectFields();
    },
    // 遍历获取表单设计对应的字段
    generateFields(list) {
      list.forEach(item => {
        if (allTargets.includes(item.type)) {
          if (item.type === 'grid') { // 栅格布局
            item.columns.forEach(column => {
              this.generateFields(column.list);
            });
          } else if (item.type === 'subform') { // 子表单
            this.allConfigFields.push(item);
            if (Array.isArray(item.subform) && item.subform.length) {
              item.subform.forEach(i => {
                i.subformFullName = item.name + '.' + i.name;
              });
              this.allConfigFields.push(...item.subform);
            }
          } else {
            this.allConfigFields.push(item);
          }
        }
      });
    },
    setSelectData(oldFieldsList) {
      if (!Array.isArray(oldFieldsList) || !oldFieldsList.length) return;
      const noticeSelectData = {};
      const filterSelectData = {};
      oldFieldsList.forEach(field => {
        field.isShow && (noticeSelectData[field.key] = true);
        field.isFilter && (filterSelectData[field.key] = true);
      });
      this.allConfigFields.forEach(field => {
        if (noticeSelectData[field.key]) field.isShow = true;
        if (filterSelectData[field.key]) field.isFilter = true;
      });
    },
    // 记录所有人员选择字段
    allUserSelectFields() {
      this.$nextTick(() => {
        const allUserFields = this.allConfigFields.filter(item => item.type === 'user' && !item.isSubTable);
        this.$store.dispatch('setAllUserFields', allUserFields || []);
      });
    },
    storeAllDeptSelectFields() {
      this.$nextTick(() => {
        const allDeptFields = this.allConfigFields.filter(item => item.type === 'department');
        this.$store.dispatch('setAllDeptFields', allDeptFields || []);
      });
    },
    handleSelect(val) {
      this.activeIndex = val;
    },
    validateAllSettings() {
      const promise = [];
      promise.push(this.$refs['listSettingRef'].validateForm()); // 列表设置
      promise.push(this.$refs['listSettingRef'].$refs['exportSettingRef'].validateForm()); // 列表设置
      promise.push(this.$refs['listSettingRef'].$refs['cardSettingRef'].validate()); // 列表设置
      promise.push(this.$refs['eventSettingRef'].validateForm()); // 事件设置
      promise.push(this.$refs['noticeSettingRef'].validateForm()); // 通知模板
      promise.push(this.$refs['permissionsSettingRef'].validateForm()); // 权限设置
      promise.push(this.$refs['dataSettingRef'].validateForm()); // 权限设置
      return new Promise((resolve, reject) => {
        Promise.all(promise).then(res => {
          const validateResult = res.every(item => !!item);
          validateResult ? resolve(true) : reject('请完善高级设置信息');
        }).catch(msg => {
          reject(msg);
        });
      });
    },
    getAdvancedData() {
      const params = {};
      params.process = this.$refs['processSettingRef'].getData();
      if (!this.isFixed) {
        params.list = this.$refs['listSettingRef'].getData();
        params.exportList = this.$refs['listSettingRef'].$refs['exportSettingRef'].getData();
        params.card = this.$refs['listSettingRef'].$refs['cardSettingRef'].getData();
        params.event = this.$refs['eventSettingRef'].getData();
        params.notice = this.$refs['noticeSettingRef'].getData();
        params.permissions = this.$refs['permissionsSettingRef'].getData();
        params.dataForm = this.$refs['dataSettingRef'].getData();
      }
      return params;
    },
    // 设置详情回调数据
    setData(data, type) {
      const advancedData = _.cloneDeep(data);
      this.processType = type;
      const { process, list, event, notice, permissions, dataForm, exportList, card } = advancedData;
      this.$refs['processSettingRef'].setData(process);
      if (!this.isFixed) {
        list && this.$refs['listSettingRef'] && this.$refs['listSettingRef'].setData(list);
        exportList && this.$refs['listSettingRef'] && this.$refs['listSettingRef'].$refs['exportSettingRef'].setData(exportList);
        this.$refs['listSettingRef'] && this.$refs['listSettingRef'].$refs['cardSettingRef'].setData(card);
        event && this.$refs['eventSettingRef'] && this.$refs['eventSettingRef'].setData(event);
        notice && this.$refs['noticeSettingRef'] && this.$refs['noticeSettingRef'].setData(notice, this.formList);
        permissions && this.$refs['permissionsSettingRef'] && this.$refs['permissionsSettingRef'].setData(permissions);
        dataForm && this.$refs['dataSettingRef'] && this.$refs['dataSettingRef'].setData(dataForm);
      }
    },
    // 初始化列表字段，引用时会调用
    initList(formList) {
      if (!this.isFixed) {
        this.$refs['listSettingRef'] && this.$refs['listSettingRef'].initList(formList);
        this.$refs['listSettingRef'] && this.$refs['listSettingRef'].$refs['exportSettingRef'].initList(formList);
        this.$refs['listSettingRef'] && this.$refs['listSettingRef'].$refs['cardSettingRef'].initList(formList);
        this.$refs['eventSettingRef'] && this.$refs['eventSettingRef'].initOrdersField();
        this.$refs['noticeSettingRef'] && this.$refs['noticeSettingRef'].initList(formList);
        this.$refs['dataSettingRef'] && this.$refs['dataSettingRef'].initList(formList);
      }
    },
    // 初始化数据同步
    initDataList(formList) {
      if (!this.isFixed) {
        this.$refs['dataSettingRef'] && this.$refs['dataSettingRef'].initList(formList);
        this.$refs['listSettingRef'] && this.$refs['listSettingRef'].$refs['exportSettingRef'].initList(formList);
      }
    },
    // 高级设置菜单权限
    showSettingTab(id) {
      const permissionIds = ['5', '6'];
      if (!permissionIds.includes(id)) return true;
      if (id === '5') return this.showPermissionsSetting;
      if (id === '6') return this.showSyncData;
    }
  }
};
</script>

<style scoped lang="scss">
.advanced-setting-container {
  display: flex;
  height: 100%;
  &::v-deep {
    .el-menu {
      .el-menu-item {
        text-align: center;
        font-size: 14px;
        padding: 0 !important;
        width: 112px;
        height: 32px;
        line-height: 32px;
        margin: 0 auto 12px;
        .is-dot {
          top: 8px;
        }
      }
      .is-active {
        font-weight: bold;
        background-color: #edeef2;
      }
    }
  }
  .setting-menu {
    min-width: 148px;
    height: 100%;
    padding-top: 24px;
    .setting-menu-icon {
      width: 16px;
      height: 16px;
      margin-right: 4px;
    }
  }
  .setting-main-container {
    padding: 16px;
    background-color: #f4f4f4;
    height: calc(100vh - 48px);
    width: calc(100vw - 148px);
    .setting-main-content {
      background-color: #fff;
      padding: 16px 24px;
      height: 100%;
      overflow-y: auto;
    }
  }
}
</style>
